<?php

namespace app\admin\controller;

use app\BaseController;
use think\App;
use think\facade\Db;

/**
 * Businessapi小店数据接口
 * 
 */


class Businessapi extends BaseController
{

    protected $app_id = "";
    protected $secret = "";
    protected $auth_code = "";
    protected $access_token = "";
    protected $model = null;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->app_id = '7368326312273903632';
        $this->secret = '4fda475abf872ce3e87e9c5825a05b240f3fc2c7';
        $this->auth_code = '91ab291661bf5522a95903dbfa184d3d34c4e7a0';
        $this->access_token = 'aaf097749d1094879be11c23ba81b4f56ba70e7a';
    }

    //更新之前的
    public function integrated_get_old()
    {
        $advplat = table('advplat')
            ->where('adv_id',6)
            ->where('updatetime_automatic','>','2023-10-01')
            ->order('integrated_time asc')
            ->limit('2')
            ->select()
            ->toarray();
            
        if(!empty($advplat)){
            foreach ($advplat as $k=>$v) {
                $update = array();
                if(!empty($v['updatetime_automatic']) && strtotime($v['updatetime_automatic']) > 1672502400){
                    $this->integrated_get($v,$v['updatetime_automatic']);
                    $update['updatetime_automatic'] = date('Y-m-d', strtotime($v['updatetime_automatic'])- 24 * 3600);
                }
                $update['integrated_time'] = time();
                $advplat = table('advplat')
                    ->where('id',$v['id'])
                    ->update($update);
            }
        }
        return success('操作成功');
    }

    //实时更新
    public function integrated_get_for()
    {
        $advplat = table('advplat')
            ->where('adv_id',6)
            ->order('integrated_time_new asc')
            ->limit('2')
            ->select()
            ->toarray();
        if(!empty($advplat)){
            foreach ($advplat as $k=>$v) {
                $updatetime_automatic = date('Y-m-d',time());
                $this->integrated_get($v,$updatetime_automatic);
                
                $update = array();
                $update['integrated_time_new'] = time();
                $advplat = table('advplat')
                    ->where('id',$v['id'])
                    ->update($update);
            }
        }
        return success('操作成功');
    }
    /**
    * @param array params
    */
    public function integrated_get($v,$date_end)
    {
        $date_start = date('Y-m-d', strtotime($date_end)- 24 * 3600 * 2);
        $advertiser_id = $v['account'];
        $advplat_id = $v['id'];
        $admin_id = $v['admin_ids'];
        $dimensions = ['ad_id', 'stat_time_day'];
        $dimensions = json_encode($dimensions, true);
        $url = "https://business-api.tiktok.com/open_api/v1.3/report/integrated/get/?advertiser_id=".$advertiser_id."&page=1&data_level=AUCTION_ADVERTISER&report_type=BASIC&dimensions=".$dimensions."&page_size=1000&start_date=".$date_start."&end_date=".$date_end;
        // halt($url);die;
        
        $metrics = [
            "campaign_id",
            "campaign_name",
            "spend",
            "ad_name",
            "onsite_shopping_roas",
            "total_onsite_shopping_value",
            "real_time_conversion",
            "conversion"
        ];
        
        $filtering[0]["field_name"] = "ad_status";
        $filtering[0]["filter_type"] = "IN";
        $filterValue = ["STATUS_ALL"];
        $encodedFilterValue = json_encode($filterValue); 
        $filtering[0]["filter_value"] = $encodedFilterValue;
        $filtering = json_encode($filtering, true);
        
        $metrics = json_encode($metrics, true);
        $url = "https://business-api.tiktok.com/open_api/v1.3/report/integrated/get/?advertiser_id=".$advertiser_id."&page=1&data_level=AUCTION_AD&report_type=BASIC&dimensions=".$dimensions."&metrics=".$metrics."&filtering=".$filtering."&page_size=1000&start_date=".$date_start."&end_date=".$date_end;
        
        $return0 = geturl_business($url, $this->access_token);
        // halt($return0);
        $return = json_decode($return0, true);
        $return2 = array();
        if(isset($return['data']['list']) && !empty($return['data']['list'])){
            foreach ($return['data']['list'] as $k=>$v) {
                $advplat = table('advertisingapi')
                    ->where('date_start',$v['dimensions']['stat_time_day'])
                    ->where('account_id',$v['dimensions']['advertiser_id'])
                    ->find();
                if(empty($advplat)){
                    $insert = array();
                    $insert['advplat_id'] = $advplat_id;
                    $insert['date_start'] = $v['dimensions']['stat_time_day'];
                    $insert['account_id'] = $v['dimensions']['advertiser_id'];
                    $insert['spend'] = $v['metrics']['spend'];
                    $insert['impressions'] = $v['metrics']['impressions'];
                    $return2[] = table('advertisingapi')->insert($insert);
                }else{
                    $update = array();
                    $update['spend'] = $v['metrics']['spend'];
                    $update['impressions'] = $v['metrics']['impressions'];
                    $return2[] = table('advertisingapi')
                        ->where('date_start',$v['dimensions']['stat_time_day'])
                        ->where('account_id',$v['dimensions']['advertiser_id'])
                        ->update($update);
                } 
                //广告表也存
                $advplat2 = table('advertising')
                    ->where('create_time',$v['dimensions']['stat_time_day'])
                    ->where('plat_account',$advplat_id)
                    ->find();
                if(empty($advplat2)){
                    $insert = array();
                    $insert['plat'] = 6;
                    $insert['admin_id'] = $admin_id;
                    $insert['plat_account'] = $advplat_id;
                    $insert['create_time'] = $v['dimensions']['stat_time_day'];
                    $insert['cost'] = $v['metrics']['spend'];
                    $return2[] = table('advertising')->insert($insert);
                } else{
                    $insert = array();
                    $insert['cost'] = $v['metrics']['spend'];
                    $return2[] = table('advertising')
                        ->where('create_time',$v['dimensions']['stat_time_day'])
                        ->where('plat_account',$advplat_id)
                        ->update($insert);
                } 
            }
        }
        return success('操作成功', $return2);
    }

    /**
    * 修改广告账户归属状态
    * @param array params
    */
    public function update_advaccount_log()
    {
        $update['status'] = 'hidden';
        $return = table('advaccount_log')
            ->where('updatetime','>=',1)
            ->where('updatetime','<=',time())
            ->where('status','normal')
            ->update($update);
        return success('操作成功', $return);
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 广告账户列表
     * @author zhangheng
     */
    public function getApiAdvaccountsList($params = [])
    {  
        $app_id = $this->app_id;
        $secret = $this->secret;
        $url = "https://business-api.tiktok.com/open_api/v1.3/oauth2/advertiser/get/?app_id=".$app_id."&secret=".$secret;
        $return = geturl_business($url, $this->access_token);
        $return = json_decode($return, true);
        if(isset($return['data']['list']) && !empty($return['data']['list'])){
            foreach ($return['data']['list'] as $adv) {
                //更新广告账户
                $advaccount = table('advplat')
                    ->where('account', $adv['advertiser_id'])
                    ->where('adv_id',6)
                    ->find();
                $data = [
                    'adv_id' => 6,
                    'account' => $adv['advertiser_id'],
                    'account_main' => $adv['advertiser_name'],
                ];
                if(empty($advaccount)){
                    table('advplat')->insert($data);
                } else {
                    table('advplat')->where('id', $advaccount['id'])->update($data);
                }
            }
        }
        return success('操作成功', $return);
    }
    
    /**
    * 方法详情
    * @param array params
    */
    public function adinfo()
    {
        $id = input('id');
        $url = "https://business-api.tiktok.com/open_api/v1.3/ad/get/?advertiser_id=".$id;
        $return = geturl_business($url, $this->access_token);
        $return = json_decode($return, true);
        halt($return);
    }
    
    /**
     * 获取token
     * @param array params
     */
    public function token()
    {
        $url = "https://business-api.tiktok.com/open_api/v1.3/oauth2/access_token/";
        $data['app_id'] = $this->app_id;
        $data['auth_code'] = $this->auth_code;
        $data['secret'] = $this->secret;
        // halt($data);
        $return0 = $this->posturl_token($url, $data);
        $return = json_decode($return0, true);
        halt($return);
    }

    
    function posturl_token($url, $data)
    {
        $data = (is_array($data)) ? json_encode($data, JSON_UNESCAPED_UNICODE) : $data;
        $headerArray = array("Content-Type:application/json;");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
    
}
